'use strict';

const BaseController = require('../core/base_controller');
const model = 'SysDict'

class Controller extends BaseController {
    /**
     * 数组转tree
     * @param list
     * @returns {*[]}
     */
    composeTree(list = []) {
        const data = JSON.parse(JSON.stringify(list)) // 浅拷贝不改变源数据
        const result = []
        if (!Array.isArray(data)) {
            return result
        }
        data.forEach(item => {
            delete item.children
        })
        const map = {}
        data.forEach(item => {
            map[item.id] = item
        })
        data.forEach(item => {
            const parent = map[item.pid]
            if (parent) {
                (parent.children || (parent.children = [])).push(item)
            } else {
                result.push(item)
            }
        })
        return result
    }


    /**
     * GET
     * /api
     * 分页查询 page pageSize keyword
     */
    async index() {
        try {
            const result = await this.ctx.service.commonService.pagingQuery({...this.ctx.query, model: model});
            this.success(result);
        } catch (error) {
            this.error(error);
        }
    }

    /**
     * Get
     * tree
     * @returns {Promise<void>}
     */
    async tree() {
        try {
            const result = await this.ctx.service.commonService.pagingQuery({...this.ctx.query, model: model});
            this.success(this.composeTree(result.rows));
        } catch (error) {
            this.error(error);
        }
    }

    /**
     * GET
     * /api/:id
     * 通过id查询
     */
    async show() {
        try {
            const result = await this.service.commonService.findByPk({id: this.ctx.params.id, model: model});
            this.success(result);
        } catch (error) {
            this.error(error);
        }
    }

    /**
     * DELETE
     * /api/:id
     * 通过id删除
     */
    async destroy() {
        try {
            const result = await this.service.commonService.delete({id: this.ctx.params.id, model: model});
            this.success(result);
        } catch (error) {
            this.error(error);
        }
    }

    /**
     * PUT
     * /api/:id
     */
    async update() {
        let id = this.ctx.params.id;
        let body = this.ctx.request.body;
        try {
            let result = await this.service.commonService.insertOrUpdate({data: {id, ...body}, model: model});
            this.success(result);
        } catch (error) {
            this.error(error);
        }
    }

    /**
     * POST
     * /api
     */
    async create() {
        let body = this.ctx.request.body;
        try {
            let result = await this.service.commonService.insertOrUpdate({data: body, model: model});
            this.success(result);
        } catch (error) {
            this.error(error);
        }
    }
}

module.exports = Controller;
